<template>
  <header class="header">
    <el-row type="flex" justify="space-between" align="middle" style="height: 100%;">
      <el-col :span="6">
        <!-- 左侧标题 + 返回按钮 -->
        <div class="logo-container">
          <el-button v-if="showBack" icon="el-icon-arrow-left" circle @click="goBack" style="margin-right: 10px;"></el-button>
          <h2 class="logo">{{ title }}</h2>
        </div>
      </el-col>

      <el-col :span="6">
        <!-- 右侧用户信息 -->
        <div class="user-info">
          <UserAvatar
            :src="userAvatar"
            size="medium"
            shape="circle"
            class="header-avatar"
            :uploadable="false"
            @update:src="newAvatar => userAvatar = newAvatar"
          />
          <span style="margin-left: 8px;">欢迎，{{ displayName }}</span>
          <el-button @click="logout" size="mini" style="margin-left: 15px;">退出</el-button>
        </div>
      </el-col>
    </el-row>
  </header>
</template>

<script>
import UserAvatar from '@/components/UserAvatar.vue';

export default {
  components: { UserAvatar },
  props: {
    showBack: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '聊天室'
    }
  },
  data() {
    return {
      userAvatar: ''
    };
  },
  computed: {
    currentUser() {
      return this.$store.state.user || {};
    },
    displayName() {
      return this.currentUser.nickname || this.currentUser.username || '匿名用户';
    }
  },
  watch: {
    currentUser(newUser) {
      if (newUser && newUser.avatar) {
        this.userAvatar = newUser.avatar;
      }
    }
  },
  mounted() {
    if (this.currentUser && this.currentUser.avatar) {
      this.userAvatar = this.currentUser.avatar;
    }
  },
  methods: {
    goBack() {
      this.$router.back(); // 直接调用 Vue Router 提供的方法
    },
    logout() {
      this.$store.dispatch('logout');
      this.$router.push('/');
    }
  }
};
</script>

<style scoped>
.header {
  background-color: #ffffff;
  padding: 0 20px;
  height: 60px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  border-bottom: 1px solid #e8e8e8;
}

.logo {
  margin: 0;
  font-size: 20px;
  color: #333;
  display: inline-block;
  vertical-align: middle;
}

.logo-container {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
}
</style>